package com.hngy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hngy.common.R;
import com.hngy.domain.Category;
import com.hngy.domain.Dish;
import com.hngy.domain.DishFlavor;
import com.hngy.dto.DishDto;
import com.hngy.service.CategoryService;
import com.hngy.service.DishFlavorService;
import com.hngy.service.DishService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author LiKe
 * @date 2021/12/28 15:30
 */
@RestController
@RequestMapping("/dish")
@Slf4j
@Api(tags = "菜品相关接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R add(@RequestBody DishDto dishDto){
        log.info("dishDto = {}",dishDto.toString());

        dishService.add(dishDto);
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("添加成功！");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R pageDish(int page,int pageSize,String name){
        log.info("page = {},pageSize = {},name = {}",page,pageSize,name);

        return R.success(dishService.pageDishType(page,pageSize,name));
    }

    /**
     * 查询单个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        log.info("id = {}",id);

        DishDto dishDto = dishService.getDishDto(id);


        return R.success(dishDto);
    }

    /**
     * 修改
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto){
        log.info("dishDto = {}",dishDto.toString());

        dishService.updateDishFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改成功！");
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteByIds(String[] ids){
        log.info("ids = {}",ids.length);

        dishService.deleteById(ids);


        return R.success("删除成功！");
    }

    /**
     * 修改售卖状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R status(@PathVariable int status,@RequestParam List<Long> ids){
        log.info("length = {}",ids);

        dishService.updateStatus(status,ids);

        return R.success("修改成功！");
    }

    /*@GetMapping("/list")
    public R listType(Long categoryId){
        log.info("categoryId = {}",categoryId);

        //根据分类id查询菜品
        List<Dish> list = dishService.listType(categoryId);

        return R.success(list);
    }*/
    @GetMapping("/list")
    public R getBycategoryId(Dish categoryId){
        log.info(categoryId.toString());
        List<DishDto> dtoList = null;
        //获取Redis中的缓存
        //动态构造key
        String key = "dish_" + categoryId.getCategoryId() + "_" + categoryId.getStatus();//dish_1397844391040167938_1
        //先从redis中获取缓存数据
        dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dtoList != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dtoList);
        }

        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //select * dish where categoryId = ?
        queryWrapper.eq(categoryId.getCategoryId() != null,Dish::getCategoryId,categoryId.getCategoryId());
        //起售
        queryWrapper.eq(Dish::getStatus,1);
        //排序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

         dtoList = list.stream().map((item)->{
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);
            //分类id
            Long itemCategoryId = item.getCategoryId();

            Category category = categoryService.getById(itemCategoryId);

            if (category != null){
                dishDto.setCategoryName(category.getName());
            }
            //菜品id
            Long dishId = item.getId();

            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);
        return R.success(dtoList);
    }
}
